﻿//#define RESTARTDEBUG
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace MikadoShooter
{
    public static class FileHelper
    {
        private static readonly string SaveDir;
        private static readonly string SavePath;

        static FileHelper()
        {
            SaveDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Application.ProductName);
            SavePath = Path.Combine(SaveDir, "save.bin");

#if RESTARTDEBUG
            if (File.Exists(SavePath))
                File.Delete(SavePath);
#endif
        }

        public static bool Save(LevelData saveLevel, bool silent = true)
        {
            IFormatter formatter = new BinaryFormatter();
            StreamWriter writer = null;

            if (!Directory.Exists(SaveDir))
                Directory.CreateDirectory(SaveDir);

            try
            {
                writer = new StreamWriter(SavePath);
                formatter.Serialize(writer.BaseStream, saveLevel);
            }
            catch
            {
                if (silent)
                    return false;

                throw;
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }

            return true;
        }

        public static bool Load(out LevelData saveLevel, bool silent = true)
        {
            IFormatter formatter = new BinaryFormatter();
            StreamReader reader = null;
            saveLevel = null;

            try
            {
                reader = new StreamReader(SavePath);
                saveLevel = formatter.Deserialize(reader.BaseStream) as LevelData;

                if (saveLevel == null)
                    throw new NullReferenceException("saveLevel == null");
            }
            catch
            {
                if (silent)
                    return false;

                throw;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }

            return true;
        }
    }
}
